import Util from '../Util.js';
import Msg from './Message.js';
import Win from './Win.js';
import TaskBar from './TaskBar.js';
import Http from './Http.js';

export default class Desktop {
    constructor(idSelector, app) {
        const id = idSelector.startsWith('#') ? idSelector : `#${idSelector}`;
        this.desktopCtrl = document.querySelector(id);
        this.app = app;
        // Desktop.save(this.app);
    }
    // 创建桌面网格
    build(idSelector) {
        const id = idSelector.startsWith('#') ? idSelector : `#${idSelector}`;
        // 生成桌面网格
        const desktopIconContainer = document.querySelector(id);
        let HTMLString = '';
        for (let i = 0; i < 170; i++) {

            if (typeof this.app[`${Util.addZero(i, 3)}`] !== 'undefined') {
                HTMLString += `
                    <li>
                        <label>
                            <input type="radio" name="focusController">
                            <div data-icon-pos="${Util.addZero(i, 3)}" id="desktopIcon_${Util.addZero(i, 3)}" class="desktop-icon" draggable="true">
                                <img data-icon-pos="${Util.addZero(i, 3)}" draggable="false" src="${this.app[`${Util.addZero(i, 3)}`].icon}" alt="">
                                <span data-icon-pos="${Util.addZero(i, 3)}" draggable="false">${this.app[`${Util.addZero(i, 3)}`].name}</span>
                            </div>
                        </label>
                    </li>`;
            } else {
                HTMLString += `
                    <li>
                        <label>
                            <input type="radio" name="focusController">
                            <div id="desktopIcon_${Util.addZero(i, 3)}" class="desktop-icon" draggable="true">
                            
                            </div>
                        </label>
                    </li>`;
            }
        }
        desktopIconContainer.innerHTML = HTMLString;
    }

    // 桌面图标绑定事件
    bindIcon(clsSelector) {

        const cls = clsSelector.startsWith('.') ? clsSelector : `.${clsSelector}`;

        // 桌面图标设置--拖动-网格
        const desktopIcons = document.querySelectorAll(cls);

        // 桌面图标事件设置
        for (let i = 0; i < desktopIcons.length; i++) {
            // 单击选中
            desktopIcons[i].addEventListener('click', (event) => {
                if (desktopIcons[i].children.length <= 0) {
                    event.preventDefault();
                    // 点击空白选中空白checkbox 用于清除图标选中效果
                    this.desktopCtrl.checked = true;
                }
            });
            // 双击打开
            desktopIcons[i].addEventListener('dblclick', (event) => {
                const target = Util.getTarget(event, 'DIV', 'IMG', 'SPAN');
                const id = target.id.substring(target.id.length - 3);
                if (id) {
                    Win.open(this, id);
                }
            });
            // 拖动事件
            desktopIcons[i].addEventListener('dragstart', (event) => {
                // 有图标的格子才能拖动
                if (event.target.children.length !== 0) {
                    event.target.parentElement.children[0].checked = true;
                    event.dataTransfer.setData("Text", event.target.id);
                    desktopIcons[i].removeAttribute('style');
                } else {
                    event.preventDefault();
                }
            });

            desktopIcons[i].parentElement.addEventListener('dragover', (event) => {
                event.preventDefault();
            });

            function appendChildren(target, elems) {
                for (let i = 0; i < elems.length; i++) {
                    target.appendChild(elems[i]);
                }
            }

            desktopIcons[i].addEventListener('drop', (event) => {
                event.preventDefault();
                const data = event.dataTransfer.getData("Text");

                if (event.target.children.length <= 0 && event.target.tagName === 'DIV') {
                    const elems = document.getElementById(data).children;
                    const oldIndex = elems[0].parentElement.getAttribute('data-icon-pos');
                    const newIndex = event.target.id.substring(event.target.id.length - 3);
                    // 通过旧index找到数据并修改
                    this.app[newIndex] = this.app[oldIndex];

                    // 清除原位置data-icon-pos
                    elems[0].parentElement.removeAttribute('data-icon-pos');
                    // 新位置设置data-icon-pos
                    event.target.setAttribute('data-icon-pos', newIndex);
                    elems[0].setAttribute('data-icon-pos', newIndex);
                    elems[1].setAttribute('data-icon-pos', newIndex);
                    // 获取焦点
                    event.target.parentElement.children[0].checked = true;
                    for (let i = 0; i <= elems.length; i++) {
                        appendChildren(event.target, elems);
                    }

                    // 修改窗口及内部所有关联元素的id属性
                    try {
                        document.getElementById(`win_${oldIndex}`).setAttribute('id', `win_${newIndex}`);
                        document.getElementById(`winCtrl_${oldIndex}`).setAttribute('id', `winCtrl_${newIndex}`);
                        document.getElementById(`winContainer_${oldIndex}`).setAttribute('id', `winContainer_${newIndex}`);
                        document.getElementById(`winMin_${oldIndex}`).setAttribute('id', `winMin_${newIndex}`);
                        document.getElementById(`winMax_${oldIndex}`).setAttribute('id', `winMax_${newIndex}`);
                        document.getElementById(`winClose_${oldIndex}`).setAttribute('id', `winClose_${newIndex}`);
                    } catch {}

                    TaskBar.removeTask(oldIndex, false);
                    TaskBar.addTask(newIndex);

                    // 删除旧数据
                    delete this.app[oldIndex];
                    // 上传数据
                    Http.upload('app', this.app);
                }
            });
        }
    }

    // 选中桌面控件
    focus() {
        this.desktopCtrl.checked = true;
    }

    hasApp(projectName) {
        let flag = false;
        for (let id in this.app) {
            if (this.app[id].projectName === projectName) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    addApp(data) {
        // 加入缓存
        this.app[data.id] = data.app;

        // 添加桌面图标
        const container = document.getElementById(`desktopIcon_${data.id}`);
        container.setAttribute('data-icon-pos', data.id);
        container.style.opacity = 0;
        container.innerHTML = `
            <img data-icon-pos="${data.id}" draggable="false" src="${data.app.icon}" alt="">
            <span data-icon-pos="${data.id}" draggable="false">${data.app.name}</span>
        `;
        Util.animate(container, {
            opacity: 1,
        });
    }

    deleteApp(id) {

        const icon = document.getElementById(`desktopIcon_${id}`);
        Util.animate(icon, {
            opacity: 0,
        }, () => {
            // 删除桌面图标
            icon.innerHTML = '';
            icon.removeAttribute('data-icon-pos');
            // 删除隐藏的窗口
            const win = document.getElementById(`win_${id}`);
            if (win) {
                win.remove();
            }
            if (this.app[id].onTaskBar) {
                TaskBar.removeTask(id);
                TaskBar.removeFromTaskBar(this, id);
            }
            // 删除desktop中的缓存
            delete this.app[id];
        });
    }

    // static save(app) {
    //     const timer = Util.timer();

    //     timer.set(() => {
    //         window.localStorage['appData'] = JSON.stringify(app);
    //     }, 1000);
    // }
}